<template>
  <div class="tools-div">
    <el-form size="small">
      <el-row>
        <el-form-item label="状态">
          <el-select v-model="queryDto.status" placeholder="请选择">
            <el-option label="全部" :value="-1"></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" style="margin-left: 20px;">
          <el-input v-model="queryDto.roleName" placeholder="分类名称"></el-input>
        </el-form-item>
        <el-button type="primary" size="small" @click="searchSysRole" style="margin-left: 20px;">搜索</el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <!-- 按钮 -->
  <el-button style="margin-bottom: 10px" type="primary" size="small" @click="InsertTJ()">添加</el-button>

  <!-- 懒加载的树形表格 -->
  <el-table
  :data="list"
  style="width: 100%"
  row-key="id"
  border
  lazy
  :load="fetchData"
  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
>
  <el-table-column prop="categoryName" label="分类名称" />
  <el-table-column prop="orderNum" label="排序" />
  <el-table-column prop="status" label="状态" #default="scope">
    {{ scope.row.status == 1 ? '正常' : '停用' }}
  </el-table-column>
  <el-table-column prop="createTime" label="创建时间" />
  <el-table-column label="操作" align="center" width="280" #default="scope">
    <el-button type="primary" size="small" @click="Insert(scope.row)">添加子目录</el-button>
    <el-button type="warning" size="small" @click="Update(scope.row)">编辑</el-button>
    <el-button type="danger" size="small" @click="deleteById(scope.row)">删除</el-button>
  </el-table-column>
</el-table>

  <!-- 对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form label-width="120px">
        <el-form-item label="分类名称">
          <el-input v-model="sysMenu.categoryName"/>
        </el-form-item>
        <el-form-item v-if="!sysMenu.hasChildren" label="上级部门" prop="categoryId">
          <el-tree-select
            v-model="sysMenu.categoryId"
            :data="deptOptions"
            :props="{ value: 'id', label: 'name', isLeaf: 'leaf' }"
            :load="loadNode"
            lazy
            @visible-change="handleVisibleChange"
            value-key="id"
            placeholder="选择上级部门"
            check-strictly/>
      </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="sysMenu.orderNum" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="sysMenu.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PictureById, findAll, SavePicture, UpdatePicture, RemovePicture } from '@/service/api/material/classify';


// 定义list属性模型
const list = ref([])

const queryDto = ref({
roleName: null,
status: -1
});

const searchSysRole = () => {
zy();
}

const resetData = () => {
queryDto.value = {}
}

const deptOptions = ref([]);

const dialogVisible = ref(false)
const dialogTitle = ref('')

const sysMenu = ref({
id: "",
categoryName: "",
status: 1,
orderNum: 1,
categoryId: "",
hasChildren:""
})

// 页面初始化完毕以后请求后端接口查询数据
onMounted(() => {
zy();
})

const zy = async () => {
  // const params = {
  //   status: queryDto.value.status,
  //   name: queryDto.value.roleName
  // };
  const { code, data, message } = await findAll();
  if (code === 200) {
    list.value = data; // 更新表格数据
  } else {
    ElMessage.error(message);
  }
};

const isLoaded = ref(false); // 标志位，确保数据只加载一次
// 当下拉框显示/隐藏时触发
const handleVisibleChange = async (visible) => {
if (visible && !isLoaded.value) {
    try {
      const res = await PictureById(0);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载
    } catch (error) {
          console.error("加载数据失败:", error);
        }
      }
};

// 懒加载子节点
const loadNode = async (node, resolve) => {
  if (node.level === 0) {
    return resolve(deptOptions.value);
  }

  try {
    const parentId = node.data.id;
    const res = await PictureById(parentId);
    const nodes = res.data.map(item => ({
      id: item.id,
      name: item.categoryName,
      leaf: !item.hasChildren
    }));
    resolve(nodes);
  } catch (error) {
    console.error("加载子节点失败:", error);
    resolve([]); // 返回空数组，避免页面卡死
  }
};

// 加载数据的方法
const fetchData = async (row, treeNode, resolve) => {
const { code, data, message } = await PictureById(row.id)
resolve(data)
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
sysMenu.value.imageUrl = response.data
}

const submit = async () => {
if (!sysMenu.value.id) {
  const { code, message, data } = await SavePicture(sysMenu.value)
  if (code === 200) {
    dialogVisible.value = false
    ElMessage.success('操作成功')
  
  } else {
    ElMessage.error(message)
  }
} else {
  const { code, message, data } = await UpdatePicture(sysMenu.value)
  if (code === 200) {
    dialogVisible.value = false
    ElMessage.success('操作成功')
  } else {
    ElMessage.error(message)
  }
}
zy()
fetchData();
}

const deleteById = (row) => {
ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '温馨提示', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning',
}).then(async () => {
  const { code, message } = await RemovePicture(row.id)
  if (code === 200) {
    ElMessage.success('删除成功')
    zy();
    fetchData();
  } else {
    ElMessage.error(message)
  }
})
}

// 修改数据
const Update = async(row) => {

row.categoryId=row.categoryId===0?null:row.categoryId;
if(row.categoryId!=0){
  const res = await PictureById(0);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载
}
sysMenu.value = row
dialogVisible.value = true;
dialogTitle.value = "修改"
}


const InsertTJ=()=>{
  sysMenu.value = {
  id: "-99",
  categoryName: "",
  categoryId: "",
  status: 1,
  orderNum: 1,
  hasChildren:true
}
dialogVisible.value = true;
dialogTitle.value = "添加"
}
// 添加数据
const Insert = async(row) => {
    const res = await PictureById(row.categoryId);
      deptOptions.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isLoaded.value = true; // 标记为已加载

sysMenu.value = {
  id: "",
  categoryName: "",
  categoryId: row.id,
  status: 1,
  orderNum: 1
}
dialogVisible.value = true;
dialogTitle.value = "添加"
}
</script>

<style scoped>
.search-div {
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ebeef5;
border-radius: 3px;
background-color: #fff;
}
</style>